package com.qiall.boot.userservice.Impl.user.activity;

import com.qiall.assertutil.Assert;
import com.qiall.boot.userservice.data.entity.OrganizationInfo;
import com.qiall.boot.userservice.data.entity.UserInfo;
import com.qiall.boot.userservice.data.mapper.OrganizationInfoMapper;
import com.qiall.boot.userservice.data.mapper.UserMapper;
import com.qiall.common.exception.BusinessException;
import com.qiall.common.exception.ResultCode;
import com.qiall.common.request.BaseActivity;
import com.qiall.user.ability.entity.CreateUserDTO;
import com.qiall.user.ability.entity.UserInfoDTO;
import com.qiall.user.ability.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author 吴金辉
 */
@Component
public class CreateUserPreCheckActivity extends BaseActivity<CreateUserDTO, UserInfoDTO> {

    @Autowired
    private UserMapper userMapper;


    @Autowired
    private UserService userService;

    @Autowired
    private OrganizationInfoMapper organizationInfoMapper;

    @Override
    public void handler(CreateUserDTO request, UserInfoDTO response) {
        // 参数校验
        paramsCheck(request, response);
        // 权限校验
        authCheck(request, response);
    }

    /**
     * 参数校验
     * @param request
     * @param response
     */
    private void paramsCheck(CreateUserDTO request, UserInfoDTO response) {
        // 校验账号是否重复
        Assert.notNull(request.getRoleId(), "角色不能为空");
        Assert.notNull(request.getPhone(), "电话不能为空");
        Assert.notNull(request.getAccount(),"账号不能为空");
        Assert.notNull(request.getPassword(),"密码不能为空");
        // 校验电话是否已经被注册
        UserInfo userInfo = userMapper.selectByAccount(request.getAccount());
        if (userInfo != null) {
            throw new BusinessException(ResultCode.DATA_ALREADY_EXIST, "用户已经被注册");
        }

    }

    /**
     * 判断添加用户
     * @param request
     * @param response
     */
    private void authCheck(CreateUserDTO request, UserInfoDTO response) {

        // 当前登陆用户

        if(request.getOrgId()==null){
            return;
        }
        UserInfoDTO userInfoDTO = userService.getUserInfoByAuthCode(request).getBody();
        // 只有组织的管理员才有权限添加组织成员
       OrganizationInfo organizationInfo= organizationInfoMapper.select(request.getOrgId());
        Assert.isTrue((organizationInfo.getOrgLeaderId().equals(userInfoDTO.getUserId())),"没有所属组织权限");

    }
}
